package controller;

import exception.PointOutOfBoundsException;
import view.HighlightPanel;
import search.XYLocalizer;
import utils.BrowserLogger;
import view.HtmlPanel;
import treeview.NodeView;
import treeview.unit.AbstractUnitView;
import view.Selection;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

/**
 * Created by Pavel Nikolaev
 */
public class SelectionManager implements MouseListener, MouseMotionListener {
    private HighlightPanel myHighlighter;
    private XYLocalizer myLocalizer;
    private Selection mySelection;

    public SelectionManager(HighlightPanel highlightPanel) {
        myHighlighter = highlightPanel;
        myLocalizer = new XYLocalizer();
        mySelection = new Selection();
    }

    public void mouseClicked(MouseEvent e) {
        mySelection.clear();
        myHighlighter.setSelection(mySelection);
    }

    public void mousePressed(MouseEvent e) {
        NodeView global = ((HtmlPanel)e.getComponent()).getView();
        AbstractUnitView local = myLocalizer.searchByCoordinates(global, e.getX(), e.getY());
        int markOffset = local.findOffset(e.getX());
        mySelection.setMarkOffset(markOffset);
        mySelection.setMarkViewIndex(local.getIndex());
    }

    public void mouseReleased(MouseEvent e) {
        processSelectionEnd(e);
        myHighlighter.setSelection(mySelection);
    }

    public void mouseEntered(MouseEvent e) {
        /*ignored*/
    }

    public void mouseExited(MouseEvent e) {
        /*ignored*/
    }

    public void mouseDragged(MouseEvent e) {
        processSelectionEnd(e);
        if (!mySelection.isEmpty()) myHighlighter.setSelection(mySelection);
    }

    public void mouseMoved(MouseEvent e) {
        /*ignored*/
    }

    public void processSelectionEnd(MouseEvent e) {
        NodeView global = ((HtmlPanel)e.getComponent()).getView();
        AbstractUnitView local = myLocalizer.searchByCoordinates(global, e.getX(), e.getY());
        int dotOffset = local.findOffset(e.getX());
        mySelection.setDotOffset(dotOffset);
        mySelection.setDotViewIndex(local.getIndex());
    }

}
